package com.zhima.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zhima.dto.ZhimaOjResult;
import com.zhima.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

import static com.zhima.config.OjGatewayProperties.whitelist;
import static com.zhima.constant.SystemConstant.AUTHORIZATION_HEADER;
import static com.zhima.exception.ErrorCode.*;


@Component
@Slf4j
@Order(0)
public class GlobalAuthFilter implements GlobalFilter {
    @Autowired
    private TokenStore tokenStore;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 拿到请求的url
        String requestUrl = exchange.getRequest().getPath().value();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        // 白名单上的路径放行
        for (String url : whitelist) {
            if (pathMatcher.match(url, requestUrl)) {
                return chain.filter(exchange);
            }
        }

        //检查token是否存在
        String token = getToken(exchange);
        if (StrUtil.isBlank(token)) {
            return buildReturnMono(NOT_AUTHORIZATION, exchange);
        }
        OAuth2AccessToken oAuth2AccessToken;
        try {
            // 判断是否是有效的token
            oAuth2AccessToken = tokenStore.readAccessToken(token);
            // 判断是否过期
            boolean expired = oAuth2AccessToken.isExpired();
            if (expired) {
                return buildReturnMono(TOKEN_HAS_EXPIRED, exchange);
            }
            // 放行
            return chain.filter(exchange);
        } catch (InvalidTokenException e) {
            log.info("认证令牌无效: {}", token);
            return buildReturnMono(TOKEN_NOT_VALID, exchange);
        }
    }

    private Mono<Void> buildReturnMono(ErrorCode errorCode, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        // 将错误信息写入响应
        byte[] bits = JSONUtil.toJsonStr(ZhimaOjResult.fail(errorCode)).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 从请求头中取出token
     *
     * @param exchange
     * @return
     */
    private String getToken(ServerWebExchange exchange) {
        String tokenStr = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION_HEADER);
        if (StrUtil.isBlank(tokenStr)) {
            return null;
        }
        // Bearer token
        String token = tokenStr.split(" ")[1];
        if (StrUtil.isBlank(token)) {
            return null;
        }
        return token;
    }
}
